#include <jni.h>
#include <string>
#include <MediaPlayer.h>
#include "JniLayer.h"
#include "Demux.h"
#include <android/native_window_jni.h>

static shared_ptr<MediaPlayer>
getInstanceInternal(JNIEnv *env, jobject thiz)
{
    auto ptr =  reinterpret_cast<shared_ptr<MediaPlayer> *>(env->GetLongField(thiz,
                                                                                fields.MediaPlayer.mInstanceID));

    return *ptr;
}

static void
setInstance(JNIEnv *env, jobject thiz, shared_ptr<MediaPlayer>* mediaPlayer)
{
    env->SetLongField(thiz,
                      fields.MediaPlayer.mInstanceID,
                      (jlong)(mediaPlayer));
}


extern "C" JNIEXPORT void JNICALL
Java_com_example_simpleplayer_MediaPlayer_NewInstance(
        JNIEnv* env,
        jobject thiz/* this */) {
//    auto mediaPlayer = make_shared<MediaPlayer>();

    auto mediaPlayer = new shared_ptr<MediaPlayer>(new MediaPlayer);

    setInstance(env,thiz,mediaPlayer);
}

extern "C" JNIEXPORT int JNICALL
Java_com_example_simpleplayer_MediaPlayer_nativeSetDataSource(
        JNIEnv* env,
        jobject thiz, jstring path) {

    auto mediaPlayer = getInstanceInternal(env,thiz);

    const char *jcstr = (env)->GetStringUTFChars(path, 0);
    mediaPlayer->setDataSource(jcstr);
    (env)->ReleaseStringUTFChars(path, jcstr);

    return 0;
}

extern "C" JNIEXPORT int JNICALL
Java_com_example_simpleplayer_MediaPlayer_nativestart(
        JNIEnv* env,
        jobject thiz) {
    auto mediaPlayer = getInstanceInternal(env,thiz);

    mediaPlayer->start();
    return 0;
}

extern "C" JNIEXPORT int JNICALL
Java_com_example_simpleplayer_MediaPlayer_nativepause(
        JNIEnv* env,
        jobject thiz/* this */) {
    auto mediaPlayer = getInstanceInternal(env,thiz);

    mediaPlayer->pause();
    return 0;
}

extern "C" JNIEXPORT int JNICALL
Java_com_example_simpleplayer_MediaPlayer_nativesetSurface(
        JNIEnv* env,
        jobject thiz,/* this */jobject surface) {
    auto mediaPlayer = getInstanceInternal(env,thiz);

    ANativeWindow *theNativeWindow = ANativeWindow_fromSurface(env, surface);

    mediaPlayer->setSurface(theNativeWindow);
    return 0;
}

extern "C" JNIEXPORT int JNICALL
Java_com_example_simpleplayer_MediaPlayer_nativestop(
        JNIEnv* env,
        jobject thiz/* this */) {
    auto mediaPlayer = getInstanceInternal(env,thiz);

    mediaPlayer->stop();
    return 0;
}
